package com.ty.config;


import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.net.UnknownHostException;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        //执行序列化的逻辑
        Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        // 序列化的时候，自动推断类型，将类型信息作为属性写入JSON
        // 反序列化时候，根据类型的全类名，序列化成对应的对象实例
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);

        jsonRedisSerializer.setObjectMapper(objectMapper);


        //我们所有的key 使用RedisSerializer.string()作为序列化工具
        template.setKeySerializer(RedisSerializer.string());
        //hash的小key 使用RedisSerializer.string()作为序列化工具
        template.setHashKeySerializer(RedisSerializer.string());
        // template  设置value 序列化工具
        template.setValueSerializer(jsonRedisSerializer);
        //hash的value 使用Jackson2JsonRedisSerializer作为序列化工具
        template.setHashValueSerializer(jsonRedisSerializer);


        return template;
    }
}
